﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;
using NetCoreCMS.PayAPI.chinabankpc;

namespace NetCoreCMS.Web.Areas.Payments.Controllers
{
    public class ChinaBankPCController : AreasController
    {
        public IUser_rechargeService _user_recharge { get; set; }
        public IOrdersService _orders { get; set; }
        public ISite_paymentService _site_payment { get; set; }
        public IPaymentService _payment { get; set; }
        public IUser_point_logService _user_point_log { get; set; }
        public IActionResult Index()
        {
            //读取站点配置信息
            int site_payment_id = 0; //订单支付方式

            //=============================获得订单信息================================
            string order_no = CMSRequest.GetFormString("pay_order_no", HttpContext).ToUpper();
            decimal order_amount = CMSRequest.GetFormDecimal("pay_order_amount", 0, HttpContext);
            string user_name = CMSRequest.GetFormString("pay_user_name", HttpContext);
            string subject = CMSRequest.GetFormString("pay_subject", HttpContext);
            //以下收货人信息
            string receive_name = string.Empty; //收货人姓名
            string receive_address = string.Empty; //收货人地址
            string receive_zip = string.Empty; //收货人邮编
            string receive_phone = string.Empty; //收货人电话
            string receive_mobile = string.Empty; //收货人手机
                                                  //检查参数是否正确
            if (order_no == "" || order_amount == 0)
            {
                return ToError("对不起，您提交的参数有误！");
            }
            if (order_no.StartsWith("R")) //R开头为在线充值订单
            {
                User_recharge model = _user_recharge.GetModel(order_no);
                if (model == null)
                {
                    return ToError("对不起，您充值的订单号不存在或已删除！");
                }
                if (model.amount != order_amount)
                {
                    return ToError("对不起，您充值的订单金额与实际金额不一致！");
                }
                site_payment_id = model.payment_id; //站点支付方式ID

                //取得用户信息
                Users userModel = _users.GetModel(model.user_id);
                if (userModel == null)
                {
                    return ToError("对不起，用户账户不存在或已删除！");
                }
                receive_name = userModel.nick_name;
                receive_address = userModel.address;
                receive_phone = userModel.telphone;
                receive_mobile = userModel.mobile;
            }
            else //B开头为商品订单
            {
                Orders model = _orders.GetModel(order_no);
                if (model == null)
                {
                    return ToError("对不起，您支付的订单号不存在或已删除！");
                }
                if (model.order_amount != order_amount)
                {
                    return ToError("对不起，您支付的订单金额与实际金额不一致！");
                }
                site_payment_id = model.payment_id; //站点支付方式ID
                receive_name = model.accept_name;
                receive_address = model.address;
                receive_zip = model.post_code;
                receive_phone = model.telphone;
                receive_mobile = model.mobile;
            }
            if (!string.IsNullOrEmpty(user_name))
            {
                user_name = "支付会员：" + user_name;
            }
            else
            {
                user_name = "匿名用户";
            }
            var site_paymentModel = _site_payment.GetList().FirstOrDefault(a => a.payment_id == site_payment_id);
            var paymentModel = _payment.GetModel(site_payment_id);
            //===============================加密签名==================================
            Config config = new Config(site_paymentModel, paymentModel, sysConfig, HttpContext);
            string moneytype = "CNY";
            // 拼凑加密串=订单金额+币种+订单号+商户号+返回地址+商户MD5密钥
            string signtext = order_amount + moneytype + order_no + config.Partner + config.Return_url + config.Key;
            string md5info = Utils.MD5(signtext).ToUpper();

            //===============================请求参数==================================
            //把请求参数打包成数组
            SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();
            sParaTemp.Add("v_mid", config.Partner); //商户编号
            sParaTemp.Add("v_oid", order_no); //网站订单号
            sParaTemp.Add("v_amount", order_amount.ToString()); //订单总金额
            sParaTemp.Add("v_moneytype", moneytype); //币种
            sParaTemp.Add("v_url", config.Return_url); //返回地址
            sParaTemp.Add("remark2", "[url:=" + config.Notify_url + "]"); //回调地址
            sParaTemp.Add("v_md5info", md5info); //MD5校验码
            sParaTemp.Add("remark1", sysConfig.webname + "-" + subject + user_name); //订单描述

            sParaTemp.Add("v_rcvname", receive_name); //收货人姓名
            sParaTemp.Add("v_rcvaddr", receive_address); //收货人地址
            sParaTemp.Add("v_rcvtel", receive_phone); //收货人电话
            sParaTemp.Add("v_rcvpost", receive_zip); //收货人邮编
            sParaTemp.Add("v_rcvmobile", receive_mobile); //收货人手机号

            //构造即时到帐接口表单提交HTML数据，无需修改
            Service chinabank = new Service(site_paymentModel, paymentModel, sysConfig, HttpContext);
            string sHtmlText = chinabank.BuildFormHtml(sParaTemp, "post", "确认");
            return Content(sHtmlText);
        }
        public IActionResult Notify_Url()
        {
            string v_oid; //订单号
            string v_pstatus; //支付状态码
                              //20（支付成功，对使用实时银行卡进行扣款的订单）；
                              //30（支付失败，对使用实时银行卡进行扣款的订单）；
            string v_pstring; //支付状态描述
            string v_pmode; //支付银行
            string v_md5str; //MD5校验码
            string v_amount; //支付金额
            string v_moneytype; //币种		
            string remark1;//备注1
            string remark2;//备注1
            int site_payment_id = 0; //站点支付方式ID

            v_oid = CMSRequest.GetString("v_oid", HttpContext).ToUpper(); //订单号
            v_pstatus = CMSRequest.GetString("v_pstatus", HttpContext);
            v_pstring = CMSRequest.GetString("v_pstring", HttpContext);
            v_pmode = CMSRequest.GetString("v_pmode", HttpContext);
            v_md5str = CMSRequest.GetString("v_md5str", HttpContext);
            v_amount = CMSRequest.GetString("v_amount", HttpContext);
            v_moneytype = CMSRequest.GetString("v_moneytype", HttpContext);
            remark1 = CMSRequest.GetString("remark1", HttpContext);
            remark2 = CMSRequest.GetString("remark2", HttpContext);
            if (v_oid.StartsWith("R")) //充值订单
            {
                site_payment_id = _user_recharge.GetModel(v_oid).payment_id;
            }
            else if (v_oid.StartsWith("B")) //商品订单
            {
                site_payment_id = _orders.GetModel(v_oid).payment_id;
            }
            if (site_payment_id == 0)
            {
                return Content("error");
            }
            var site_paymentModel = _site_payment.GetList().FirstOrDefault(a => a.payment_id == site_payment_id);
            var paymentModel = _payment.GetModel(site_payment_id);
            // 拼凑加密串
            Config config = new Config(site_paymentModel, paymentModel, sysConfig, HttpContext);
            string signtext = v_oid + v_pstatus + v_amount + v_moneytype + config.Key;
            signtext = Utils.MD5(signtext).ToUpper();

            if (signtext == v_md5str && v_pstatus.Equals("20"))
            {
                //成功状态
                if (v_oid.StartsWith("R")) //充值订单
                {
                    User_recharge model = _user_recharge.GetModel(v_oid);
                    if (model == null)
                    {
                        return Content("error");
                    }
                    if (model.status == 1) //已成功
                    {
                        return Content("ok");
                    }
                    if (model.amount != decimal.Parse(v_amount))
                    {
                        return Content("error");
                    }
                    bool result = _user_recharge.Confirm(v_oid);
                    if (!result)
                    {
                        return Content("error");
                    }
                }
                else if (v_oid.StartsWith("B")) //商品订单
                {
                    Orders model = _orders.GetModel(v_oid);
                    if (model == null)
                    {
                        return Content("error");
                    }
                    if (model.payment_status == 2) //已付款
                    {
                        return Content("ok");
                    }
                    if (model.order_amount != decimal.Parse(v_amount))
                    {
                        return Content("error");
                    }
                    bool result = _orders.UpdateField(v_oid, "status=2,payment_status=2,payment_time='" + DateTime.Now + "'");
                    if (!result)
                    {
                        return Content("error");
                    }

                    //扣除积分
                    if (model.point < 0)
                    {
                        _user_point_log.Add(model.user_id, model.user_name, model.point, "换购扣除积分，订单号：" + model.order_no, false);
                    }
                }

                //成功状态
                return Content("ok");
            }

            //失败状态
            return Content("error");
        }
        public IActionResult Return_Url()
        {
            string v_oid;        // 订单号
            string v_pstatus; // 支付状态码
                              //20（支付成功，对使用实时银行卡进行扣款的订单）；
                              //30（支付失败，对使用实时银行卡进行扣款的订单）；
            string v_pstring; //支付状态描述
            string v_pmode;   //支付银行
            string v_amount;  //支付金额
            string v_moneytype;   //币种		
            string remark1;   // 备注1
            string remark2;   // 备注1
            string v_md5str;
            int site_payment_id = 0; //站点支付方式ID

            v_oid = CMSRequest.GetString("v_oid", HttpContext).ToUpper();
            v_pstatus = CMSRequest.GetString("v_pstatus", HttpContext);
            v_pstring = CMSRequest.GetString("v_pstring", HttpContext);
            v_pmode = CMSRequest.GetString("v_pmode", HttpContext);
            v_md5str = CMSRequest.GetString("v_md5str", HttpContext);
            v_amount = CMSRequest.GetString("v_amount", HttpContext);
            v_moneytype = CMSRequest.GetString("v_moneytype", HttpContext);
            remark1 = CMSRequest.GetString("remark1", HttpContext);
            remark2 = CMSRequest.GetString("remark2", HttpContext);
            if (v_oid.StartsWith("R")) //充值订单
            {
                site_payment_id = _user_recharge.GetModel(v_oid).payment_id;
            }
            else if (v_oid.StartsWith("B")) //商品订单
            {
                site_payment_id = _orders.GetModel(v_oid).payment_id;
            }
            var site_paymentModel = _site_payment.GetModel(site_payment_id);
            var paymentModel = _payment.GetModel(site_payment_id);
            //找到站点支付方式ID开始验证
            if (site_payment_id > 0)
            {
                // 拼凑加密串
                Config config = new Config(site_paymentModel, paymentModel, sysConfig, HttpContext);
                string signtext = v_oid + v_pstatus + v_amount + v_moneytype + config.Key;
                signtext = Utils.MD5(signtext).ToUpper();
                if (signtext == v_md5str)
                {
                    if (v_pstatus.Equals("20"))
                    {
                        //成功状态
                        return Redirect("/Web/Payment/Index?action=succeed&order_no=" + v_oid);
                    }
                }
            }

            //失败状态
            return Redirect("/Web/Payment/Index?action=error");
        }
    }
}